from zipline.api import order, symbol, record
import numpy as np

def initialize(context):
    # 策略参数
    context.period = 20
    context.devfactor = 2.0
    context.asset = symbol('AAPL')  # 示例资产，实际使用时替换
    
def handle_data(context, data):
    # 获取历史价格数据
    prices = data.history(
        context.asset, 
        'price', 
        bar_count=context.period, 
        frequency='1d'
    )
    
    # 计算布林带
    moving_avg = np.mean(prices)
    moving_std = np.std(prices)
    upper_band = moving_avg + context.devfactor * moving_std
    lower_band = moving_avg - context.devfactor * moving_std
    
    # 当前价格
    current_price = data.current(context.asset, 'price')
    
    # 交易逻辑
    if not context.portfolio.positions[context.asset].amount:  # 无持仓
        if current_price <= lower_band:  # 触及下轨
            order(context.asset, 1)  # 买入
    elif current_price >= upper_band:  # 触及上轨
        order(context.asset, -1)  # 卖出
        
    # 记录数据（可选）
    record(
        price=current_price,
        upper_band=upper_band,
        lower_band=lower_band,
        moving_avg=moving_avg
    )